<template>
                   <!--面包屑-->
<div style="margin-bottom: 30px">
 <el-breadcrumb separator="/">
   <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
   <el-breadcrumb-item>

        <router-link to="/LineList">线路管理</router-link>
   </el-breadcrumb-item>
   <el-breadcrumb-item>修改新路信息</el-breadcrumb-item>
 </el-breadcrumb></div>
    <el-form ref="ruleFormRef" style="max-width: 550px" :model="form" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="线路名称：" prop="lineName">
            <el-input v-model="form.lineName" placeholder="请输入线路名称" />
        </el-form-item>
       
   <el-form-item label="起点：" prop="">
           <el-select v-model="selectedProvince" @change="handleProvinceChange" placeholder="请选择省份" style="width: 130px;">
          <el-option v-for="item in provinces" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        <el-select v-model="selectedCity" @change="handleCityChange" placeholder="请选择城市" style="width: 130px;">
          <el-option v-for="item in cities" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        <el-select v-model="selectedCounty" @change="handleCountyChange" placeholder="请选择区县" style="width: 130px;">
          <el-option v-for="item in counties" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        </el-form-item>
   

        <el-form-item label="起点详细地址:" prop="startingPointAddress">
            <el-input v-model="form.startingPointAddress" placeholder="请输入起点详细地址" />
        </el-form-item>
        <el-form-item label="终点：" prop="">
             <el-select v-model="selectedProvince1" @change="handleProvinceChange1" placeholder="请选择省份" style="width: 130px;">
          <el-option v-for="item1 in provinces1" :key="item1.provinceCode" :label="item1.provinceName" :value="item1.provinceCode" />
        </el-select>
        <el-select v-model="selectedCity1" @change="handleCityChange1" placeholder="请选择城市" style="width: 130px;">
          <el-option v-for="item1 in cities1" :key="item1.provinceCode" :label="item1.provinceName" :value="item1.provinceCode" />
        </el-select>

        <el-select v-model="selectedCounty1" @change="handleCountyChange1" placeholder="请选择区县" style="width: 130px;">
          <el-option v-for="item1 in counties1" :key="item1.provinceCode" :label="item1.provinceName" :value="item1.provinceCode"  />
        </el-select>
        </el-form-item>
        <el-form-item label="终点详细地址:" prop="endAddress">
            <el-input v-model="form.endAddress" placeholder="请输入终点详细地址" />
        </el-form-item>
        <el-form-item label="是否是外协:" prop="outsourcedUnitsIsno">
            <el-select v-model="form.outsourcedUnitsIsno" placeholder="请选择是否是外协">
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
            </el-select>
        </el-form-item>
        <el-form-item label="货主姓名:" prop="cargoOwnerName">
            <el-input v-model="form.cargoOwnerName" placeholder="请输入货主姓名" />
        </el-form-item>
        <el-form-item label="货主手机号:" prop="cargoOwnerPhone">
            <el-input v-model="form.cargoOwnerPhone" placeholder="请输入货主手机号" />
        </el-form-item>
        <el-form-item label="货主单位:" prop="cargoOwnerUnitName">
            <el-input v-model="form.cargoOwnerUnitName" placeholder="请输入货主单位" />
        </el-form-item>
        <el-form-item label="备注:" prop="lineNotes">
            <el-input v-model="form.lineNotes" type="textarea" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                修改
            </el-button>
            <el-button @click="resetForm">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script lang="ts" setup>
//起点
interface provinc {
    provinceCode: any
    provinceName: any
    cities: any
}
interface citi {
    provinceCode: any
    provinceName: any
    cities: any
}
interface counti {
    provinceCode: any
    provinceName: any
    cities: any
}
const provinces = ref<provinc[]>([])
const cities = ref<citi[]>([])
const counties = ref<counti[]>([])
const selectedProvince = ref("")
const selectedCity = ref("")
const selectedCounty = ref("")

// 处理省份变化
const handleProvinceChange = () => {
    const province = provinces.value.find(p => p.provinceCode === selectedProvince.value);
    if (province) {
        cities.value = province.cities;  // 更新城市列表
        selectedCity.value = '';
        selectedCounty.value = '';
        counties.value = [];
        form.startingProvince = province.provinceName; // 设置选中的省份名称
    }
}

// 处理城市变化
const handleCityChange = () => {
    const city = cities.value.find(c => c.provinceCode === selectedCity.value);
    if (city) {
        counties.value = city.cities;  // 更新县列表
        selectedCounty.value = '';
        form.startingCity = city.provinceName; // 设置选中的城市名称
    }
}

// 处理县变化
const handleCountyChange = () => {
    const county = counties.value.find(c => c.provinceCode === selectedCounty.value);
    if (county) {
        form.startingCounty = county.provinceName; // 设置选中的县名称
    }
}

// 从指定 URL 获取数据
async function fetchData(url: any) {
    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        if (!response.ok) throw new Error('网络响应不正常');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("数据获取错误:", error);
        ElMessage({
            message: "数据加载失败，请重试。",
            type: "error"
        });
    }
}
import  { ElMessage } from 'element-plus'
// 省改变时的处理函数
const onProvinceChange = () => {
    // 清空城市和区的选择
    selectedCity.value = '';
    selectedCounty.value = '';
    counties.value = [];
    // 获取所选省的城市
    const province = provinces.value.find(p => p.provinceCode === selectedProvince.value);
    cities.value = province ? province.cities : [];
};
// 市改变时的处理函数
const onCityChange = () => {
    // 清空区的选择
    selectedCounty.value = '';
    // 获取所选市的区
    const city = cities.value.find(c => c.provinceCode === selectedCity.value);
    counties.value = city ? city.cities : [];
};
//终点
interface provinc1 {
    provinceCode: any
    provinceName: any
    cities: any
}
interface citi1 {
    provinceCode: any
    provinceName: any
    cities: any
}
interface counti1 {
    provinceCode: any
    provinceName: any
    cities: any
}
const provinces1 = ref<provinc1[]>([])
const cities1 = ref<citi1[]>([])
const counties1 = ref<counti1[]>([])
const selectedProvince1 = ref("")
const selectedCity1 = ref("")
const selectedCounty1 = ref("")

// 处理省份变化
const handleProvinceChange1 = () => {
    const province1 = provinces1.value.find(p => p.provinceCode === selectedProvince1.value);
    if (province1) {
        cities1.value = province1.cities;  // 更新城市列表
        selectedCity1.value = '';
        selectedCounty1.value = '';
        counties1.value = [];
        form.endProvince = province1.provinceName; // 设置选中的省份名称
    }
}

// 处理城市变化
const handleCityChange1 = () => {
    const city1 = cities1.value.find(c => c.provinceCode === selectedCity1.value);
    if (city1) {
        counties1.value = city1.cities;  // 更新县列表
        selectedCounty1.value = '';
        form.endCity = city1.provinceName; // 设置选中的城市名称
    }
}

// 处理县变化
const handleCountyChange1 = () => {
    const county1 = counties1.value.find(c => c.provinceCode === selectedCounty1.value);
    if (county1) {
        form.endCounty = county1.provinceName; // 设置选中的县名称
    }
}

// 从指定 URL 获取数据
async function fetchData1(url: any) {
    try {
        const response1 = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        if (!response1.ok) throw new Error('网络响应不正常');
        const data1 = await response1.json();
        return data1;
    } catch (error) {
        console.error("数据获取错误:", error);
        ElMessage({
            message: "数据加载失败，请重试。",
            type: "error"
        });
    }
}

// 省改变时的处理函数
const onProvinceChange1 = () => {
    // 清空城市和区的选择
    selectedCity1.value = '';
    selectedCounty1.value = '';
    counties1.value = [];
    // 获取所选省的城市
    const province1 = provinces1.value.find(p => p.provinceCode === selectedProvince1.value);
    cities1.value = province1 ? province1.cities : [];
};
// 市改变时的处理函数
const onCityChange1 = () => {
    // 清空区的选择
    selectedCounty1.value = '';
    // 获取所选市的区
    const city1 = cities1.value.find(c => c.provinceCode === selectedCity1.value);
    counties1.value = city1 ? city1.cities : [];
};
//组件
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
//变量
const form= reactive({
    
  "lineID": route.query.id,
  "companyID": "",
  "user_Id": "",
  "lineName": "",
  "startingProvince": "",
  "startingCity": "",
  "startingCounty": "",
  "startingPointAddress": "",
  "endProvince": "",
  "endCity": "",
  "endCounty": "",
  "endAddress": "",
  "outsourcedUnitsIsno": "",
  "cargoOwnerName": "",
  "cargoOwnerPhone": "",
  "cargoOwnerUnitName": "",
  "lineNotes": "",
    "lineStatus": "",
   "deletedBy": "",
    "deletedDate": "",
 "createdBy": "",
    "createdDate": "",
})
//方法
//反填线路信息
const getLineInfo = async () => {
    axios.get("/bwrite/api/Line/GetLineBy?Lineid=" + form.lineID).then(ter => {
        form.lineID = ter.data.data.lineID
        form.companyID = ter.data.data.companyID
        form.user_Id = ter.data.data.user_Id
        form.lineName = ter.data.data.lineName
        form.startingProvince = ter.data.data.startingProvince
      selectedProvince.value = ter.data.data.startingProvince
        handleProvinceChange()
        
    form.startingCity = ter.data.data.startingCity
    selectedCity.value = ter.data.data.startingCity
    handleCityChange()
        
    form.startingCounty = ter.data.data.startingCounty
     selectedCounty.value = ter.data.data.startingCounty
    handleCountyChange()
        form.startingPointAddress = ter.data.data.startingPointAddress
        
        form.endProvince = ter.data.data.endProvince
         selectedProvince1.value = ter.data.data.endProvince
        handleProvinceChange1()
       
        form.endCity = ter.data.data.endCity
         selectedCity1.value = ter.data.data.endCity
         handleCityChange1()
       
        form.endCounty = ter.data.data.endCounty
        selectedCounty1.value = ter.data.data.endCounty
    
        form.endAddress = ter.data.data.endAddress
        form.outsourcedUnitsIsno = ter.data.data.outsourcedUnitsIsno
        form.cargoOwnerName = ter.data.data.cargoOwnerName
        form.cargoOwnerPhone = ter.data.data.cargoOwnerPhone
        form.cargoOwnerUnitName = ter.data.data.cargoOwnerUnitName
        form.lineNotes = ter.data.data.lineNotes
        form.lineStatus = ter.data.data.lineStatus
         form.deletedBy = ter.data.data.deletedBy
        form.deletedDate = ter.data.data.deletedDate
          form.createdBy = ter.data.data.createdBy
         form.createdDate = ter.data.data.createdDate
    })
}
//修改线路
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//验证
const rules = reactive<FormRules>({
    lineName: [
        { required: true, message: '线路名称不能为空', trigger: 'blur' },
        
    ],
    startingPointAddress: [
        { required: true, message: '起点详细地址不能为空', trigger: 'blur' },
        
    ],
    endAddress: [
        { required: true, message: '终点详细地址不能为空', trigger: 'blur' },
        
    ],

    outsourcedUnitsIsno: [
        { required: true, message: '是否是外协不能为空', trigger: 'blur' },
        
    ],
    cargoOwnerName: [
        { required: true, message: '货主名称不能为空', trigger: 'blur' },
        
    ],
    cargoOwnerPhone: [
        { required: true, message: '货主手机号不能为空', trigger: 'blur' },
        
    ],
    cargoOwnerUnitName: [
        { required: true, message: '货主单位不能为空', trigger: 'blur' },
        
    ],
        
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
           
            axios.post("/bwrite/api/Line/UpdateLine", form).then(ter => {
                if (ter.data.code > 0) {
                    ElMessage.success("修改成功")
                  router.push("/LineList")
                } else {
                    ElMessage.error("修改失败")
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = () => {
   router.push("/LineList")
}
//钩子函数
onMounted(async () => {
    getLineInfo()//反填线路信息
    //起点
    const res = await fetchData('src/data/city.json'); // 假设这个函数是定义好的，负责获取城市数据
    if (res) {
        provinces.value = res; // 假设 res 是一个包含省的数组
        // 设置选择项
        const province = provinces.value.find(p => p.provinceName === form.startingProvince);
        if (province) {
            selectedProvince.value = province.provinceCode;
            onProvinceChange(); // 更新城市和区
            const city = cities.value.find(c => c.provinceName === form.startingCity);
            if (city) {
                selectedCity.value = city.provinceCode;
                onCityChange(); // 更新区
                const county = counties.value.find(c => c.provinceName === form.startingCounty);
                if (county) {
                    selectedCounty.value = county.provinceCode;
                }
            }
        }
    }
    //终点
    const res1 = await fetchData1('src/data/city1.json'); // 假设这个函数是定义好的，负责获取城市数据
    if (res1) {
        provinces1.value = res1; // 假设 res 是一个包含省的数组
        // 设置选择项
        const province1 = provinces1.value.find(p => p.provinceName === form.endProvince);
        if (province1) {
            selectedProvince1.value = province1.provinceCode;
            onProvinceChange1(); // 更新城市和区
            const city1 = cities1.value.find(c => c.provinceName === form.endCity);
            if (city1) {
                selectedCity1.value = city1.provinceCode;
                onCityChange1(); // 更新区
                const county1 = counties1.value.find(c => c.provinceName === form.endCounty);
                if (county1) {
                    selectedCounty1.value = county1.provinceCode;
                }
            }
        }
    }
})
</script>

